package com.zhongxi.guoyuan.OffLineShop.UI;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zhongxi.guoyuan.OffLineShop.Adapter.ShopListAdapter;
import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.Model.ItemShopInfo;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.EventBusMessage;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemData;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.widget.BounceScrollView;
import com.zhongxi.guoyuan.widget.view.LoadMoreRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/4/4.
 */

public class OffLineCateActivity extends OffLineBaseActivity {

    public static final String OFFLINE_TYPE = "offline";

    @Bind(R.id.tv_name)
    TextView mTvName;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.tools)
    LinearLayout mTools;
    @Bind(R.id.tools_scrlllview)
    BounceScrollView mToolsScrlllview;
    @Bind(R.id.tv_recommend)
    TextView mTvRecommend;
    @Bind(R.id.tv_distance)
    TextView mTvDistance;
    @Bind(R.id.tv_popularity)
    TextView mTvPopularity;
    //    @Bind(R.id.goods_pager)
//    ViewPager mGoodsPager;
    @Bind(R.id.ll_search)
    LinearLayout mLlSearch;
    @Bind(R.id.swipRefreshlayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @Bind(R.id.recycleView)
    LoadMoreRecyclerView mRecyclerView;

    private ArrayList<ProjectItemData> mProjectItemDataList;
    private TextView[] mTextViews;
    private View[] mViews;
    private ImageView[] mImageViews;
    private int orderby = 1;
    private List<ItemShopInfo> mShopInfoList = new ArrayList<>();
    private String mCateid;
    private ShopListAdapter mAdapter;

    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.activity_offline_cate);
        if (getIntent() != null) {
            mProjectItemDataList = (ArrayList<ProjectItemData>) getIntent().getSerializableExtra("catelist");
        }
        ButterKnife.bind(this);
    }

    @Override
    protected void initActionBar() {
        super.initActionBar();
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mToolbar.setNavigationIcon(R.mipmap.topback);
        mTvName.setText("线下商家分类");
    }

    @Override
    protected void initView() {
        super.initView();
        mTextViews = new TextView[mProjectItemDataList.size()];
        mViews = new View[mProjectItemDataList.size()];
        mImageViews = new ImageView[mProjectItemDataList.size()];
        for (int i = 0; i < mProjectItemDataList.size(); i++) {
            View view = UiUtils.inflate(R.layout.item_list_layout);
            view.setId(i);
            view.setOnClickListener(toolItemClick);
            TextView mTextView = (TextView) view.findViewById(R.id.text);
            ImageView mImageView = (ImageView) view.findViewById(R.id.imageView);
            mTextView.setText(mProjectItemDataList.get(i).getName());
            mTools.addView(view);
            mTextViews[i] = mTextView;
            mViews[i] = view;
            mImageViews[i] = mImageView;
        }
        mTvRecommend.setSelected(true);
        changeTextColor(0);
    }

    private View.OnClickListener toolItemClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            changeTextColor(v.getId());
            changeTextLocation(v.getId());
            mCateid = mProjectItemDataList.get(v.getId()).getId();
            page = 1;
            mSwipeRefreshLayout.setRefreshing(true);
            getShopList();
        }
    };

    @Override
    protected void initNetWork() {
        super.initNetWork();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(UiUtils.getContext()));
        mAdapter = new ShopListAdapter(mShopInfoList, 1);
        mRecyclerView.setAdapter(mAdapter);
        mSwipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.YELLOW, Color.RED);
        mSwipeRefreshLayout.setEnabled(false);
        mCateid = mProjectItemDataList.get(0).getId();
        mSwipeRefreshLayout.setRefreshing(true);
        getShopList();
    }

    @OnClick({R.id.tv_recommend, R.id.tv_distance, R.id.tv_popularity})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_recommend:
                mTvRecommend.setSelected(true);
                mTvDistance.setSelected(false);
                mTvPopularity.setSelected(false);
                orderby = 1;
                break;
            case R.id.tv_distance:
                mTvRecommend.setSelected(false);
                mTvDistance.setSelected(true);
                mTvPopularity.setSelected(false);
                orderby = 2;
                break;
            case R.id.tv_popularity:
                mTvRecommend.setSelected(false);
                mTvDistance.setSelected(false);
                mTvPopularity.setSelected(true);
                orderby = 3;
                break;
        }
        page = 1;
        mSwipeRefreshLayout.setRefreshing(true);
        getShopList();
    }

    @Override
    protected void initListener() {
        super.initListener();
        // 加载更多条目
        mRecyclerView.setOnLoadMoreListener(new LoadMoreRecyclerView.LoadMoreListener() {
            @Override
            public void loadingMore() {
                mAdapter.setLoadingState(mAdapter.LOADING);
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        new Handler().post(new Runnable() {
                            @Override
                            public void run() {
                                page++;
                                getShopList();
                            }
                        });
                    }
                }, 1000);
            }
        });

        mAdapter.setOnItemClickListener(new ShopListAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int position) {
                Intent mIntent = new Intent(UiUtils.getContext(), OffLineShopDetailActivtiy.class);
                mIntent.putExtra("offlineshopid", mShopInfoList.get(position).getId());
                startActivity(mIntent);
            }
        });

        mLlSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(OffLineCateActivity.this, OffLineSearchActivity.class));
            }
        });
    }


    private void getShopList() {
        unsubscribe();
        mDisposable = NetWork.getOffLineApi()
                .getMarketshopOfEntry(RelativeUrl.StoreList + MyApplication.getInstance().getUrl(), MyApplication.getInstance().getCheck(false),
                        page, orderby, mCateid, MyApplication.getInstance().getLongitude(), MyApplication.getInstance().getLatitude())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        mAdapter.setLoadingState(mAdapter.LOADCOMPLENT);
                        if (page == 1) {
                            mSwipeRefreshLayout.setRefreshing(false);
                            mShopInfoList.clear();
                        }
                        JSONObject jsonObject = new JSONObject(responseBody.string());
                        JSONObject safeobj = jsonObject.optJSONObject("safeobj");
                        MyApplication.getInstance().sharedPrefrences.edit().putString("now", safeobj.optString("now")).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("sk", safeobj.optString("safestring")).commit();
                        int mCode = jsonObject.optInt("code");
                        if (mCode == 1) {
                            JSONArray mJSONArray = jsonObject.optJSONArray("data");
                            JSONObject mObject = jsonObject.optJSONObject("cateInfo");
                            if (mJSONArray != null && mJSONArray.length() > 0) {
                                for (int i = 0; i < mJSONArray.length(); i++) {
                                    ItemShopInfo mItemShopInfo = ItemShopInfo.getParseObject((JSONObject) mJSONArray.get(i));
                                    String mCateName = mObject.optString(((JSONObject) mJSONArray.get(i)).optString("cateid"));
                                    mItemShopInfo.setCateName(mCateName);
                                    mShopInfoList.add(mItemShopInfo);
                                }
                                mAdapter.notifyDataSetChanged();
                            } else {
                                if (page > 1) {
                                    mAdapter.setLoadingState(mAdapter.LOADEND);
                                    page--;
                                }
                            }
                        } else if (mCode == 2816) {
                            logoutDialog();
                        } else {
                            if (page > 1) {
                                page--;
                            }
                            ToastUtil.show(getString(R.string.loseData, mCode));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mAdapter.setLoadingState(mAdapter.LOADCOMPLENT);
                        if (page == 1) {
                            mSwipeRefreshLayout.setRefreshing(false);
                        }
                        ToastUtil.show(getString(R.string.load_error_shopList));
                    }
                });
    }

    private void changeTextColor(int position) {
        for (int i = 0; i < mProjectItemDataList.size(); i++) {
            if (position != i) {
                mTextViews[i].setTextColor(getResources().getColor(R.color.bg_yield));
                mViews[i].setBackgroundColor(getResources().getColor(R.color.white));
                mImageViews[i].setVisibility(View.GONE);
            }
        }
        mTextViews[position].setTextColor(getResources().getColor(R.color.white));
        mViews[position].setBackgroundColor(getResources().getColor(R.color.postCartItem));
        mImageViews[position].setVisibility(View.VISIBLE);
    }

    private void changeTextLocation(int position) {
        int mTop = mViews[position].getTop();
        mToolsScrlllview.smoothScrollTo(0, mTop);
    }

    private void logoutDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(this).create();
        View view = UiUtils.inflate(R.layout.dialog_logout);
        TextView tv_Iknow = (TextView) view.findViewById(R.id.tv_Iknow);
        tv_Iknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                clearData();
            }
        });
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                        clearData();
                    }
                    return true;
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setView(view);
        mDialog.show();
    }

    private void clearData() {
        if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
            MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", "").commit();
            SpUtils.getInstance().saveSp("shopid", "");
            SpUtils.getInstance().saveSp("mdffline", "");
            SpUtils.getInstance().saveSp("orderid", "");
            finish();
            startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
        }
    }
}
